<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hash路由的处理</title>
</head>
<body>
    <div id="nav">
        <a href="#/page1" class="page">page1</a>
        <a href="#/page2" class="page">page2</a>
        <a href="#/page3" class="page">page3</a>
    </div>

    <div id="container"></div>

    <script>    
        

        class HashRouter {
            
            constructor() {

                this.hashURLObj = {};

                window.addEventListener('hashchange',(e) => {

                    let newURL = e.newURL;

                    let hashURL = newURL.split('#')[1];

                    const callback = this.hashURLObj[hashURL];

                    if(callback) {
                        callback();

                    }
                })

            }

            register(hashURL,fun) {

                this.hashURLObj[hashURL] = fun.bind(this); // 绑定一下好，后面执行的时候就会保证在执行上下文中
            }
            

        }

        let router = new HashRouter(); // 路由实例

        let container = document.getElementById('container');

        router.register('/page1',() => {

            container.innerHTML = '我是page1';
        })

        router.register('/page2',() => {
            container.innerHTML = '我是page2';
        })
        router.register('/page2',() => {
            container.innerHTML = '我是page2';
        })


    </script>
</body>
</html>